"""Stats Pydantic schemas for Real Estate CRM."""

from __future__ import annotations

from pydantic import Field

from ..models.enums import DemandType, LeadStage, QualityGrade
from ..schemas.base import ORMBase


class OverviewStats(ORMBase):
    """总览统计数据 Schema."""

    total_leads: int = Field(..., description="客户总数")
    new_this_week: int = Field(..., description="本周新增客户")
    conversion_rate: float = Field(..., description="转化率（0-1）")
    active_leads: int = Field(..., description="活跃客户数")
    closed_won: int = Field(..., description="成交客户数")
    closed_lost: int = Field(..., description="流失客户数")
    total_properties: int = Field(..., description="房源总数")
    monthly_visits: int = Field(..., description="本月带看数")


class SourceChartData(ORMBase):
    """来源渠道分布数据 Schema."""

    # 使用动态字段，key 是渠道名，value 是数量
    # FastAPI 会将字典序列化为 JSON 对象
    class Config:
        extra = "allow"  # 允许额外字段


class StageFunnelData(ORMBase):
    """阶段漏斗数据 Schema."""

    class Config:
        extra = "allow"  # 允许额外字段


class LeadsStatsResponse(ORMBase):
    """客户统计响应 Schema（向后兼容）."""

    by_channel: dict[str, int] = Field(default_factory=dict, description="按渠道统计")
    by_stage: dict[str, int] = Field(default_factory=dict, description="按阶段统计")


class QualityDistributionResponse(ORMBase):
    """质量等级分布响应 Schema."""

    # 质量等级分布: {"S": 5, "A": 20, "B": 35, "C": 30, "D": 10}
    S: int = Field(default=0, description="S级客户数量")
    A: int = Field(default=0, description="A级客户数量")
    B: int = Field(default=0, description="B级客户数量")
    C: int = Field(default=0, description="C级客户数量")
    D: int = Field(default=0, description="D级客户数量")


class PriorityLead(ORMBase):
    """优先跟进客户 Schema."""

    id: int
    name: str
    phone: str
    demand_type: DemandType | None
    quality_score: int | None
    quality_grade: QualityGrade | None
    stage: LeadStage | None
    updated_at: str | None  # ISO datetime string


class PriorityFollowupsResponse(ORMBase):
    """优先跟进客户列表响应 Schema."""

    total: int = Field(..., description="总数量")
    leads: list[PriorityLead] = Field(default_factory=list, description="客户列表")


class RecalculateQualityResponse(ORMBase):
    """重新计算质量评分响应 Schema."""

    updated_count: int = Field(..., description="更新数量")
    message: str = Field(..., description="提示信息")
